import React, { useState, useEffect, useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { motion } from 'framer-motion';

// 优先级颜色映射
const PRIORITY_COLORS = {
  high: 'bg-red-500',
  medium: 'bg-yellow-500',
  low: 'bg-green-500',
};

// 任务显示组件
const TaskDisplay = ({ task, onToggle, onEdit, onDelete, isOverdue, isDueSoon, getPriorityClass }) => {
  const [isEditing, setIsEditing] = useState(false);
  
  return (
    <>
      <input 
        type="checkbox" 
        checked={task.completed}
        onChange={onToggle}
        className="mt-1 h-5 w-5 text-blue-500 rounded focus:ring-blue-400"
      />
      <div className="ml-3 flex-1">
        <div className="flex items-center justify-between">
          <span className={`flex-1 ${task.completed ? 'line-through text-gray-500 dark:text-gray-400' : 'text-gray-900 dark:text-white'}`}>
            {task.title}
          </span>
          <div className="flex items-center space-x-2">
            {task.dueDate && (
              <span className={`px-2 py-1 text-xs rounded-full ${isOverdue(task.dueDate) ? 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-100' : isDueSoon(task.dueDate) ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-100' : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200'}`}>
                {new Date(task.dueDate).toLocaleDateString('zh-CN')}
                {isOverdue(task.dueDate) && ' (已过期)'}
                {isDueSoon(task.dueDate) && ' (即将到期)'}
              </span>
            )}
            <span className={`px-2 py-1 text-xs rounded-full ${getPriorityClass(task.priority)} text-white`}>
              {task.priority === 'high' && '高'}
              {task.priority === 'medium' && '中'}
              {task.priority === 'low' && '低'}
            </span>
            <button 
              onClick={() => setIsEditing(true)}
              className="p-2 text-gray-500 hover:text-blue-500 dark:text-gray-400 dark:hover:text-blue-400"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
              </svg>
            </button>
            <button 
              onClick={onDelete}
              className="p-2 text-gray-500 hover:text-red-500 dark:text-gray-400 dark:hover:text-red-400"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
              </svg>
            </button>
          </div>
        </div>
        
        {task.description && (
          <p className="mt-2 text-gray-600 dark:text-gray-300 text-sm">
            {task.description}
          </p>
        )}
        
        {task.tags && task.tags.length > 0 && (
          <div className="mt-2 flex flex-wrap gap-1">
            {task.tags.map((tag, index) => (
              <span key={index} className="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-100">
                {tag}
              </span>
            ))}
          </div>
        )}
      </div>
      
      {/* 编辑模式 */}
      {isEditing && (
        <EditModal 
          task={task} 
          onEdit={onEdit} 
          onClose={() => setIsEditing(false)} 
        />
      )}
    </>
  );
};

// 编辑模态框组件
const EditModal = ({ task, onEdit, onClose }) => {
  const [title, setTitle] = useState(task.title);
  const [description, setDescription] = useState(task.description || '');
  const [priority, setPriority] = useState(task.priority);
  const [tags, setTags] = useState(task.tags ? task.tags.join(', ') : '');
  const [dueDate, setDueDate] = useState(task.dueDate || '');
  
  // 当组件加载或任务变更时，初始化编辑表单
  useEffect(() => {
    setTitle(task.title);
    setDescription(task.description || '');
    setPriority(task.priority);
    setTags(task.tags ? task.tags.join(', ') : '');
    setDueDate(task.dueDate || '');
  }, [task]);
  
  const handleSubmit = (e) => {
    e.preventDefault();
    onEdit({
      ...task,
      title,
      description,
      priority,
      tags: tags.split(',').map(tag => tag.trim()).filter(tag => tag),
      dueDate
    });
    onClose();
  };
  
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="mt-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg w-full max-w-md">
        <h4 className="font-medium text-gray-900 dark:text-white mb-2">编辑任务</h4>
        <form onSubmit={handleSubmit}>
          <div className="space-y-2">
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white dark:bg-gray-600 text-gray-900 dark:text-white"
              placeholder="任务标题"
              required
            />
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white dark:bg-gray-600 text-gray-900 dark:text-white"
              placeholder="任务描述"
              rows="2"
            />
            <select
              value={priority}
              onChange={(e) => setPriority(e.target.value)}
              className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white dark:bg-gray-600 text-gray-900 dark:text-white"
            >
              <option value="low">低</option>
              <option value="medium">中</option>
              <option value="high">高</option>
            </select>
            <input
              type="text"
              value={tags}
              onChange={(e) => setTags(e.target.value)}
              className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white dark:bg-gray-600 text-gray-900 dark:text-white"
              placeholder="标签（用逗号分隔）"
            />
            <input
              type="date"
              value={dueDate}
              onChange={(e) => setDueDate(e.target.value)}
              className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white dark:bg-gray-600 text-gray-900 dark:text-white"
            />
            <div className="flex justify-end space-x-2">
              <button
                type="button"
                onClick={onClose}
                className="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600"
              >
                取消
              </button>
              <button
                type="submit"
                className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600"
              >
                保存
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};

const TaskItem = ({ task, onToggle, onEdit, onDelete, index, moveTask }) => {
  // 添加动画相关的引用和状态
  const itemRef = useRef(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isCompleting, setIsCompleting] = useState(false);
  
  // 拖拽功能
  const [{ isDragging }, drag] = useDrag({
    type: 'task',
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });
  
  const [{ isOver }, drop] = useDrop({
    accept: 'task',
    hover: (draggedItem) => {
      if (draggedItem.index !== index) {
        moveTask(draggedItem.index, index);
        draggedItem.index = index;
      }
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
    }),
  });
  
  // 获取优先级的显示颜色
  const getPriorityClass = (priority) => {
    return PRIORITY_COLORS[priority] || 'bg-gray-500';
  };

  // 检查截止日期是否接近
  const isDueSoon = (dueDate) => {
    if (!dueDate) return false;
    const today = new Date();
    const due = new Date(dueDate);
    const diffTime = due - today;
    const diffDays = diffTime / (1000 * 60 * 60 * 24);
    return diffDays <= 1 && diffDays >= 0;
  };
  
  // 检查是否已过期
  const isOverdue = (dueDate) => {
    if (!dueDate) return false;
    const today = new Date();
    const due = new Date(dueDate);
    return due < today;
  };

  // 处理删除动画
  const handleDelete = () => {
    // 触发动画
    setIsDeleting(true);
    // 等待动画完成后执行实际删除
    setTimeout(() => {
      onDelete(task.id);
    }, 500);
  };

  // 处理完成动画
  const handleToggle = () => {
    if (!task.completed) {
      // 触发动画
      setIsCompleting(true);
      // 等待动画完成后切换状态
      setTimeout(() => {
        onToggle(task.id);
        setIsCompleting(false);
      }, 300);
    } else {
      onToggle(task.id);
    }
  };

  return (
    <motion.li
      ref={(node) => {
        itemRef.current = node;
        drag(drop(node));
      }}
      layout
      initial={{ opacity: 0, y: 20 }}
      animate={{ 
        opacity: 1, 
        y: 0,
        scale: isDragging ? 1.05 : 1,
        boxShadow: isDragging ? '0 10px 20px rgba(0,0,0,0.2)' : '0 2px 4px rgba(0,0,0,0.1)'
      }}
      exit={{ opacity: 0, x: -100 }}
      whileHover={{ scale: 1.02 }}
      transition={{ duration: 0.2 }}
      className={`border-b border-gray-200 dark:border-gray-700 last:border-b-0 p-4 flex items-start hover:bg-gray-50 dark:hover:bg-gray-750 ${isDeleting ? 'animate-slide-out' : ''} ${isCompleting ? 'animate-complete' : ''}`}
    >
      <TaskDisplay 
        task={task}
        onToggle={handleToggle}
        onEdit={onEdit}
        onDelete={handleDelete}
        isOverdue={isOverdue}
        isDueSoon={isDueSoon}
        getPriorityClass={getPriorityClass}
      />
    </motion.li>
  );
};

export default TaskItem;